package cn.michael.dev.leetcode;

import cn.michael.dev.entity.ListNode;

/**
 * Created by hufenggang on 2021/8/11.
 *
 * 问题描述（删除链表的第N个节点）
 * 给你一个链表，删除链表的倒数第 n 个结点，并且返回链表的头结点。
 */
public class Problem19 {

    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummyHead = new ListNode(0, head);
        ListNode leftNode = dummyHead, rightNode = dummyHead;

        while (n != 0) {
            rightNode = rightNode.next;
            n--;
        }

        while (rightNode.next != null) {
            rightNode = rightNode.next;
            leftNode = leftNode.next;
        }

        leftNode.next = leftNode.next.next;
        return dummyHead.next;
    }
}
